package com.heima.behavior.service.impl;

import com.heima.behavior.config.CacheService;
import com.heima.behavior.service.ArticleInfoService;
import com.heima.common.constants.user.UserRelationConstants;
import com.heima.model.behavior.dtos.ArticleInfoDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.annotation.UserConfigurations;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ArticleInfoServiceImpl implements ArticleInfoService {
    @Autowired
    CacheService cacheService;

    /**
     * 用户操作行为记录
     *
     * @param articleInfoDto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto articleInfoDto) {
        //1.参数校验
        if (articleInfoDto == null || articleInfoDto.getArticleId() == null || articleInfoDto.getAuthorId() == null) {
            return ResponseResult.okResult();//不影响用户体验
        }
        //2.用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult();//不影响用户体验
        }
        //3.行为
        Long articleId = articleInfoDto.getArticleId();
        Integer authorId = articleInfoDto.getAuthorId();
        Integer authorApUserId = articleInfoDto.getAuthorApUserId();
        Integer userId = user.getId();
        boolean isfollow = false, islike = false, isunlike = false, iscollection = false;
        //关注
        Double scoreFollow = cacheService.zScore(UserRelationConstants.FOLLOW_LIST + userId, authorApUserId.toString());
        if (scoreFollow != null) {
            isfollow = true;
        }
        //喜欢
        Double scoreLike = cacheService.zScore(UserRelationConstants.BEHAVIOR_LIKE + userId, articleId.toString());
        if (scoreLike != null) {
            islike = true;
        }
        //不喜欢
        Double scoreUnlike = cacheService.zScore(UserRelationConstants.BEHAVIOR_UNLIKE + userId, articleId.toString());
        if (scoreUnlike != null) {
            isunlike = true;
        }
        //收藏
        Double scoreCollection = cacheService.zScore(UserRelationConstants.BEHAVIOR_COLLECTION + userId, articleId + ":" + 0);
        if (scoreCollection != null) {
            iscollection = true;
        }
        //4.封装结果返回
        Map<String, Boolean> map = new HashMap<>();
        map.put("isfollow", isfollow);
        map.put("iscollection", iscollection);
        map.put("islike", islike);
        map.put("isunlike", isunlike);
        return ResponseResult.okResult(map);

    }
}
